package com.darren.befriend.fragments;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.darren.befriend.HomeActivity;
import com.darren.befriend.R;
import com.darren.befriend.utilities.LogUtil;
import com.darren.befriend.utilities.ParseUtility;
import com.darren.befriend.views.HelveticaLTStdRoman;
import com.darren.befriend.views.MyProgressDialog;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseUser;

public class ProfileBaseFragment extends Fragment implements OnClickListener {
	protected ImageView mProfilePicView;
	protected ParseUser mCurrentUsr;
	protected static ParseUser mUsr;
	protected TextView mNameLbl, mStatusLbl, mLookForLbl, mAboutLbl,
			mAboutNameLbl, mMatchLbl, mUploadImageBtn;
	private HelveticaLTStdRoman mDistLbl;
	protected ImageView mDislikeBtn, mLikeBtn;
	private ViewGroup mActionContainer;
	private ViewGroup mMatchContainer;
	private ViewGroup mMatchContainer1;
	private ViewGroup mMatchContainer2;
	protected RelativeLayout mAfterAddFriend;
	private int[] hobbiesMatch;
	protected static boolean mVisibleLike = false, mIsFriend = false,
			isFriendRequest = false;
	private ViewGroup mView;
	protected final int REQUEST_CAMERA = 1001;
	protected final int REQUEST_GALERY = 1002;

	protected OnRelationshipChanged mOnRelationshipChanged;

	// Container Activity must implement this interface
	public interface OnRelationshipChanged {
		public void relationshipChanged(ParseUser user);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		hobbiesMatch = new int[] { R.drawable.icon_match_0,
				R.drawable.icon_match_1, R.drawable.icon_match_2,
				R.drawable.icon_match_3, R.drawable.icon_match_4,
				R.drawable.icon_match_5, R.drawable.icon_match_6,
				R.drawable.icon_match_7, R.drawable.icon_match_8 };
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = (ViewGroup) inflater.inflate(R.layout.layout_user_infor,
				container, false);

		mActionContainer = (ViewGroup) mView
				.findViewById(R.id.action_container);
		mDistLbl = (HelveticaLTStdRoman) mView
				.findViewById(R.id.user_info_distance);
		mMatchContainer1 = (ViewGroup) mView
				.findViewById(R.id.match_container_1);
		mMatchContainer2 = (ViewGroup) mView
				.findViewById(R.id.match_container_2);
		mUploadImageBtn = (TextView) mView
				.findViewById(R.id.profile_upload_image);
		mLikeBtn = (ImageView) mView.findViewById(R.id.like);
		mDislikeBtn = (ImageView) mView.findViewById(R.id.dislike);
		mMatchLbl = (TextView) mView.findViewById(R.id.match_title);
		mAfterAddFriend = (RelativeLayout) mView
				.findViewById(R.id.user_profile_friend_added_layout);
		mNameLbl = (TextView) mView.findViewById(R.id.user_info_name);
		mAboutLbl = (TextView) mView.findViewById(R.id.user_info_about);
		mLookForLbl = (TextView) mView.findViewById(R.id.user_info_look);
		mStatusLbl = (TextView) mView.findViewById(R.id.user_info_status);
		mAboutNameLbl = (TextView) mView.findViewById(R.id.user_info_name_2);
		mProfilePicView = (ImageView) mView.findViewById(R.id.user_info_icon);
		mMatchContainer = (ViewGroup) mView.findViewById(R.id.match_container);

		if (mVisibleLike) {

			if (mIsFriend) {

				mActionContainer.setVisibility(View.GONE);
				mMatchContainer.setVisibility(View.GONE);
			} else {

				mActionContainer.setVisibility(View.VISIBLE);
				mMatchContainer.setVisibility(View.VISIBLE);
			}

			mMatchLbl.setVisibility(View.VISIBLE);
		} else {

			mActionContainer.setVisibility(View.GONE);
			mMatchLbl.setVisibility(View.GONE);
			mMatchContainer.setVisibility(View.GONE);
		}

		mLikeBtn.setOnClickListener(this);
		mDislikeBtn.setOnClickListener(this);
		mUploadImageBtn.setOnClickListener(this);
		return mView;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.Fragment#onAttach(android.app.Activity)
	 */
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		try {

			mOnRelationshipChanged = (OnRelationshipChanged) activity;
		} catch (ClassCastException e) {

			throw new ClassCastException(activity.toString()
					+ " must implement OnHeadlineSelectedListener");
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		if (getActivity() instanceof HomeActivity) {

			((HomeActivity) getActivity()).showTopLogo();
			if (mVisibleLike) {

				((HomeActivity) getActivity()).showRightButtonImg(false);
				((HomeActivity) getActivity())
						.setLeftImage(R.drawable.item_back);
			} else {

				((HomeActivity) getActivity()).showRightButtonImg(true);
				((HomeActivity) getActivity())
						.setRightImage(R.drawable.item_edit);
				((HomeActivity) getActivity())
						.setLeftImage(R.drawable.icon_menu);
			}

			mCurrentUsr = ((HomeActivity) getActivity()).getCurrentUser();
			new FectchDataAsyncTask().execute();
		}
	}

	private void initAddedFriendViews(View view) {

		ImageView userImage = (ImageView) view
				.findViewById(R.id.made_friend_user_image);
		ImageView chatBtn = (ImageView) view
				.findViewById(R.id.made_friend_chat);
		TextView userName = (TextView) view
				.findViewById(R.id.made_friend_user_name);
		userName.setText(ParseUtility.getNameAndAge(mUsr));
		chatBtn.setOnClickListener(this);
		setProfileImage(userImage);
	}

	@SuppressWarnings("unchecked")
	private void configureView() {
		if (mCurrentUsr == null || mUsr == null) {

			return;
		}

		String[] namesArray = getResources().getStringArray(R.array.friend_for);
		String[] personalityArray = getResources().getStringArray(
				R.array.personality_arr);

		// distance
		mDistLbl.setText(String.format(getString(R.string.away),
				(int) ParseUtility.getDistance(mCurrentUsr, mUsr)));

		// name
		mNameLbl.setText(ParseUtility.getNameAndAge(mUsr));

		// Status
		if (ParseUtility.getStatus(mUsr)) {

			mStatusLbl.setText(getString(R.string.online_text));
		} else {

			mStatusLbl.setText(getString(R.string.offline_text));
		}

		//
		String fullname = ParseUtility.getFullName(mUsr);
		if (fullname != null && !fullname.equals("")) {

			mAboutNameLbl.setText(String.format(
					getString(R.string.user_info_name),
					fullname.replace("_local", "")));
			mMatchLbl.setText(String.format(getString(R.string.match_lbl),
					fullname.replace("_local", "")));
		}

		// user match
		ArrayList<Integer> comms = new ArrayList<Integer>();
		try {

			ParseObject meInfo1 = ParseUtility.getMeInfo(mUsr);
			List<Boolean> hobby1 = (List<Boolean>) meInfo1.get("Hobby");
			ParseObject myMeInfo = (ParseObject) mCurrentUsr.get("MeInfo");
			List<Boolean> hobby2 = (List<Boolean>) myMeInfo.get("Hobby");
			for (int i = 0; i < 9; i++) {

				if (hobby1 != null && hobby2 != null && hobby1.get(i)
						&& hobby2.get(i)) {

					comms.add(i);
				}
			}
		} catch (Exception ex) {

		}

		mMatchContainer1.removeAllViews();
		mMatchContainer2.removeAllViews();
		for (int i = 0; i < comms.size(); i++) {

			ImageView matchImg = new ImageView(getActivity());
			LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
			int left = getActivity().getResources().getDimensionPixelSize(
					R.dimen.comm_size_10dp);
			params.setMargins(left, 0, left, 0);
			matchImg.setLayoutParams(params);
			matchImg.setImageResource(hobbiesMatch[comms.get(i)]);
			if (i < 5) {

				mMatchContainer1.addView(matchImg);
			} else {

				mMatchContainer2.addView(matchImg);
			}
		}

		// look for
		StringBuilder lookFor = new StringBuilder("");
		List<Boolean> hoppy1 = ParseUtility.getHobbies(mUsr);
		if (hoppy1 != null && hoppy1.size() > 0) {

			List<String> lookingFor = new ArrayList<String>();
			for (int i = 0; i < hoppy1.size(); i++) {

				if (hoppy1.get(i)) {

					lookingFor.add(namesArray[i]);
				}
			}

			if (lookingFor.size() > 0) {

				lookFor.append(getString(R.string.looking_friend_for));
				for (int i = 0; i < lookingFor.size(); i++) {

					if (i == 0) {

						lookFor.append(lookingFor.get(i));
					} else if (i == lookingFor.size() - 1) {

						lookFor.append(" and " + lookingFor.get(i));
					} else {

						lookFor.append(", " + lookingFor.get(i));
					}
				}
			}
		}

		String him = "";

		if (ParseUtility.getGender(mUsr) == ParseUtility.MALE) {

			him = getString(R.string.he_txt);
		} else {

			him = getString(R.string.she_txt);
		}

		int personality = ParseUtility.getPersonality(mUsr);
		if (lookFor.length() > 0) {

			if (personality >= 0) {

				String tmp = String.format(getString(R.string.say),
						fullname.replace("_local", ""), him,
						personalityArray[personality], him);
				lookFor.insert(0, tmp);
			}
		} else {

			if (personality >= 0) {

				String tmp = String.format(getString(R.string.say1),
						fullname.replace("_local", ""), him,
						personalityArray[personality]);
				lookFor.append(tmp);
			}
		}

		mLookForLbl.setText(lookFor.toString());

		// about
		try {
			ParseObject meInfo = ParseUtility.getMeInfo(mUsr);
			if (meInfo != null) {

				String about = (String) meInfo.get("About");
				mAboutLbl.setText(about);
			}
		} catch (Exception ex) {

		}

		setProfileImage(mProfilePicView);
		initAddedFriendViews(mView);
	}

	private void setProfileImage(ImageView view) {
		if (mUsr == null) {

			view.setImageResource(R.drawable.tmp_full_pic);
			return;
		}

		String fullName = "";
		try {

			fullName = mUsr.get("fullName").toString();
		} catch (Exception ex) {

		}

		if (fullName == null) {

			view.setImageResource(R.drawable.tmp_full_pic);
			return;
		}

		String url = "";
		if (!fullName.contains("_local")) {

			url = String.format(getResources().getString(R.string.profile_url),
					mUsr.getUsername());
		} else {

			try {

				byte[] image = (byte[]) mUsr.get("Photo");
				Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0,
						image.length);
				view.setImageBitmap(bitmap);
				return;
			} catch (Exception e) {

				view.setImageResource(R.drawable.tmp_full_pic);
				return;
			}

		}

		((HomeActivity) getActivity()).getImageLoader().displayImage(url, view,
				((HomeActivity) getActivity()).getOptions());
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {

		case R.id.profile_upload_image:

			imageChooserDialog();
			break;
		}
	}

	private void imageChooserDialog() {

		final Dialog dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_edit_user_profile);
		dialog.getWindow().setBackgroundDrawable(
				new ColorDrawable(android.graphics.Color.TRANSPARENT));
		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();
		wlp.gravity = Gravity.CENTER;
		wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
		wlp.height = WindowManager.LayoutParams.MATCH_PARENT;
		window.setAttributes(wlp);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(true);

		// Views
		TextView cancelBtn = (TextView) dialog
				.findViewById(R.id.upload_dialog_from_cancel);
		TextView galeryBtn = (TextView) dialog
				.findViewById(R.id.upload_dialog_from_galery);
		TextView cameraBtn = (TextView) dialog
				.findViewById(R.id.upload_dialog_from_camera);

		cameraBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT,
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI.getPath());
				startActivityForResult(intent, REQUEST_CAMERA);
				dialog.dismiss();
			}
		});

		galeryBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				intent.addCategory(Intent.CATEGORY_OPENABLE);
				startActivityForResult(intent, REQUEST_GALERY);
				dialog.dismiss();
			}
		});

		cancelBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				dialog.dismiss();
			}
		});
		dialog.show();
	}

	private class FectchDataAsyncTask extends AsyncTask<Void, Void, Void> {

		private Dialog dialog;

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog = MyProgressDialog.show(getActivity(), "", "", false, false);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(java.lang.Object[])
		 */
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub

			try {
				ParseUtility.getMeInfo(mUsr);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			try {

				dialog.dismiss();
				configureView();
			} catch (Exception ex) {

				LogUtil.e("Dismis dialog", ex.getMessage());
			}
		}
	}

}
